// 路由守卫
import router from './index'
import {api} from '@/api/index'
import {localGet,localSet} from '@/Utils/storage'

// 路由白名单
const whiteList = ['/login', '/404', '/test01']

router.beforeEach(async (to, from, next) => {
  // 判断是否有token
  if (localGet('token')) {
    // 判断是否是登录页
    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    // 判断是否在白名单中
    if (whiteList.indexOf(to.path) !== -1) {
      if (to.path === '/login') {
        // 如果接到accessToken,执行获取用户信息的逻辑
        if (to.query.accessToken) {
          await loginFunc(to, next)
        }
      }
      next()
    } else {
      next('/login')
    }
  }
})

const loginFunc = async (to: any, next: any) => {
  const accessToken = to.query.accessToken
  await api.getKMInfo({ accessToken: accessToken })
    .then(async (res: any) => {
      if(res.code==0){
        localSet('token', '123456')
        localSet('userData', { account: res.data.userAccount })
        next('/')
      }else{
        alert(res.msg)
      }
    })
    .catch((err) => {
      next()
    })
}
